import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/font/Login.vue'
import Register from '@/views/font/Register.vue'
import Home from '@/views/font/Home.vue'
import Category from '@/views/font/Category.vue'
import NewBooks from '@/views/font/NewBooks.vue'
import Bestseller from '@/views/font/Bestseller.vue'
import BookDetail from '@/views/font/BookDetail.vue'
import News from '@/views/font/News.vue'
import ArticleDetail from '@/views/font/ArticleDetail.vue'
import Cart from '@/views/font/Cart.vue'
import Checkout from '@/views/font/Checkout.vue'
import Orders from '@/views/font/Orders.vue'
import OrderDetail from '@/views/font/OrderDetail.vue'
import Profile from '@/views/font/Profile.vue'
import Settings from '@/views/font/Settings.vue'

// 后台管理页面
import AdminLayout from '@/views/admin/AdminLayout.vue'
import Dashboard from '@/views/admin/Dashboard.vue'
import UserManagement from '@/views/admin/UserManagement.vue'
import AdminUserManagement from '@/views/admin/AdminUserManagement.vue'
import MerchantUserManagement from '@/views/admin/MerchantUserManagement.vue'
import RegularUserManagement from '@/views/admin/RegularUserManagement.vue'
import BookManagement from '@/views/admin/BookManagement.vue'
import CategoryManagement from '@/views/admin/CategoryManagement.vue'
import TagManagement from '@/views/admin/TagManagement.vue'
import OrderManagement from '@/views/admin/OrderManagement.vue'
import NewsManagement from '@/views/admin/NewsManagement.vue'
import ReviewManagement from '@/views/admin/ReviewManagement.vue'
import BestsellerManagement from '@/views/admin/BestsellerManagement.vue'
import AdminProfile from '@/views/admin/AdminProfile.vue'
import AdminSettings from '@/views/admin/AdminSettings.vue'

// 商家管理页面
import MerchantLayout from '@/views/merchant/MerchantLayout.vue'
import MerchantProfile from '@/views/merchant/MerchantProfile.vue'
import MerchantSettings from '@/views/merchant/MerchantSettings.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录 - 网上书城',
      requiresGuest: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      title: '注册 - 网上书城',
      requiresGuest: true
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/category',
    name: 'Category',
    component: Category,
    meta: {
      title: '图书分类 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/new-books',
    name: 'NewBooks',
    component: NewBooks,
    meta: {
      title: '新书上架 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/bestseller',
    name: 'Bestseller',
    component: Bestseller,
    meta: {
      title: '畅销榜 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/book/:id',
    name: 'BookDetail',
    component: BookDetail,
    meta: {
      title: '图书详情 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/news',
    name: 'News',
    component: News,
    meta: {
      title: '图书资讯 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/news/:id',
    name: 'ArticleDetail',
    component: ArticleDetail,
    meta: {
      title: '文章详情 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: Cart,
    meta: {
      title: '购物车 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/checkout',
    name: 'Checkout',
    component: Checkout,
    meta: {
      title: '结算 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/orders',
    name: 'Orders',
    component: Orders,
    meta: {
      title: '我的订单 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/order/:id',
    name: 'OrderDetail',
    component: OrderDetail,
    meta: {
      title: '订单详情 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta: {
      title: '个人资料 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: Settings,
    meta: {
      title: '设置 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/admin',
    component: AdminLayout,
    meta: {
      requiresAuth: true,
      requiresRole: 'admin'
    },
    children: [
      {
        path: '',
        redirect: '/admin/dashboard'
      },
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: Dashboard,
        meta: {
          title: '仪表盘 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'users',
        redirect: '/admin/users/admin'
      },
      {
        path: 'users/admin',
        name: 'AdminUsers',
        component: AdminUserManagement,
        meta: {
          title: '管理员管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'users/merchant',
        name: 'MerchantUsers',
        component: MerchantUserManagement,
        meta: {
          title: '商家管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'users/regular',
        name: 'RegularUsers',
        component: RegularUserManagement,
        meta: {
          title: '普通用户管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'books',
        name: 'AdminBooks',
        component: BookManagement,
        meta: {
          title: '图书管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'categories',
        name: 'AdminCategories',
        component: CategoryManagement,
        meta: {
          title: '分类管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'tags',
        name: 'AdminTags',
        component: TagManagement,
        meta: {
          title: '标签管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'orders',
        name: 'AdminOrders',
        component: OrderManagement,
        meta: {
          title: '订单管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'news',
        name: 'AdminNews',
        component: NewsManagement,
        meta: {
          title: '新闻管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'reviews',
        name: 'AdminReviews',
        component: ReviewManagement,
        meta: {
          title: '评论管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'bestsellers',
        name: 'AdminBestsellers',
        component: BestsellerManagement,
        meta: {
          title: '畅销管理 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'profile',
        name: 'AdminProfile',
        component: AdminProfile,
        meta: {
          title: '个人资料 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      },
      {
        path: 'settings',
        name: 'AdminSettings',
        component: AdminSettings,
        meta: {
          title: '系统设置 - 管理后台',
          requiresAuth: true,
          requiresRole: 'admin'
        }
      }
    ]
  },
  // 商家管理路由
  {
    path: '/merchant',
    component: MerchantLayout,
    meta: {
      requiresAuth: true,
      requiresRole: 'merchant'
    },
    children: [
      {
        path: '',
        redirect: '/merchant/books'
      },
      {
        path: 'books',
        name: 'MerchantBooks',
        component: BookManagement,
        meta: {
          title: '图书管理 - 商家管理中心',
          requiresAuth: true,
          requiresRole: 'merchant'
        }
      },
      {
        path: 'categories',
        name: 'MerchantCategories',
        component: CategoryManagement,
        meta: {
          title: '分类管理 - 商家管理中心',
          requiresAuth: true,
          requiresRole: 'merchant'
        }
      },
      {
        path: 'tags',
        name: 'MerchantTags',
        component: TagManagement,
        meta: {
          title: '标签管理 - 商家管理中心',
          requiresAuth: true,
          requiresRole: 'merchant'
        }
      },
      {
        path: 'bestsellers',
        name: 'MerchantBestsellers',
        component: BestsellerManagement,
        meta: {
          title: '畅销管理 - 商家管理中心',
          requiresAuth: true,
          requiresRole: 'merchant'
        }
      },
      {
        path: 'orders',
        name: 'MerchantOrders',
        component: OrderManagement,
        meta: {
          title: '订单管理 - 商家管理中心',
          requiresAuth: true,
          requiresRole: 'merchant'
        }
      },
      {
        path: 'profile',
        name: 'MerchantProfile',
        component: MerchantProfile,
        meta: {
          title: '个人资料 - 商家管理中心',
          requiresAuth: true,
          requiresRole: 'merchant'
        }
      },
      {
        path: 'settings',
        name: 'MerchantSettings',
        component: MerchantSettings,
        meta: {
          title: '商家设置 - 商家管理中心',
          requiresAuth: true,
          requiresRole: 'merchant'
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }

  // 动态导入用户store以避免循环依赖
  const { useUserStore } = await import('@/stores/user')
  const userStore = useUserStore()

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn) {
      // 未登录，重定向到登录页
      next('/login')
      return
    }

    // 验证token有效性
    const isValidToken = await userStore.checkTokenValidity()
    if (!isValidToken) {
      // token无效，重定向到登录页
      next('/login')
      return
    }

    // 检查角色权限
    if (to.meta.requiresRole && userStore.userRole !== to.meta.requiresRole) {
      // 权限不足，根据用户角色重定向到对应页面
      if (userStore.userRole === 'admin') {
        next('/admin')
      } else if (userStore.userRole === 'merchant') {
        next('/merchant')
      } else {
        next('/home')
      }
      return
    }
  }

  // 检查是否需要游客状态（已登录用户不能访问登录/注册页）
  if (to.meta.requiresGuest && userStore.isLoggedIn) {
    // 对于登录页，也要验证token有效性
    const isValidToken = await userStore.checkTokenValidity()
    if (isValidToken) {
      // token有效，根据用户角色跳转
      if (userStore.userRole === 'admin') {
        next('/admin')
      } else if (userStore.userRole === 'merchant') {
        next('/merchant')
      } else {
        next('/home')
      }
      return
    }
  }

  next()
})

export default router
